package ac.snu.cares.elgger.database;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class StateCollection {

	private static final int DB_VERSION_NUMBER = 3;
	public static final int NO_LIMIT = -1;

	public static final String START_MSG = "START LOGGING";
	public static final String STOP_MSG = "STOP LOGGING";

	private SQLiteDatabase database;
	private StateDBHelper dbHelper;

	private long newestId;

	public StateCollection(Context context, String name) {
		dbHelper = new StateDBHelper(context, name, DB_VERSION_NUMBER);
	}

	public void open() throws SQLiteException {
		database = dbHelper.getWritableDatabase();

		newestId = 0;
		String query = "SELECT COUNT(" + StateDBHelper.EVENT_ID + ") FROM "
				+ dbHelper.TABLE_NAME;
		Cursor cursor = database.rawQuery(query, null);
		if (cursor != null) {
			cursor.moveToFirst();
			newestId = cursor.getInt(0);
		}
		cursor.close();
	}

	public void close() {
		dbHelper.close();
	}

	public void put(String desc) {
		ContentValues values = new ContentValues();
		values.put(StateDBHelper.EVENT_DESCRIPTION, desc);

		insert(values);
	}

	public void put(long desc) {
		ContentValues values = new ContentValues();
		values.put(StateDBHelper.EVENT_DESCRIPTION, String.valueOf(desc));

		insert(values);
	}

	public String getLatest() {
		String ret = null;
		int goup = 0;
		while (ret == null && goup < newestId) {
			ret = get(newestId - goup);
			if (ret.equals(START_MSG) || ret.equals(STOP_MSG)) {
				ret = null;
				goup++;
			}
		}

		return ret;
	}

	public long getLatestLong() {
		long ret = -1;
		int goup = 0;
		while (ret < 0 && goup < newestId) {
			try {
				ret = Long.valueOf(get(newestId - goup));
			} catch (NumberFormatException e) {
				ret = -1;
				goup++;
			}
		}

		return ret;
	}

	public long size() {
		return newestId;
	}

	private String get(long i) {
		String query = "SELECT * FROM " + dbHelper.TABLE_NAME + " WHERE "
				+ StateDBHelper.EVENT_ID + " = " + Long.toString(i);
		Cursor cursor = database.rawQuery(query, null);
		String desc = null;
		while (cursor.moveToNext()) {
			desc = cursor.getString(2);
		}
		cursor.close();

		return desc;
	}

	private void insert(ContentValues values) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date(System.currentTimeMillis()));

		values.put(StateDBHelper.OCCUR_TIME, time);

		long insertedId = database.insert(dbHelper.TABLE_NAME, null, values);
		if (insertedId == -1) {
			Log.e("StateCollection", "can't record the event on"
					+ dbHelper.TABLE_NAME);
		} else {
			newestId = insertedId;
		}
	}
}